package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: E-Commerce-Month-01
 * @BelongsPackage: com.bwie.filter
 * @Author: asus
 * @CreateTime: 2025-10-16  16:44
 * @Description: 网关拦截器
 * @Version: 1.0
 */
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //  获取 request 和 response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        // 1、校验白名单
        if(path.contains("pwdLogin") || path.contains("upload")){
            return chain.filter(exchange);
        }
        // 2、校验 token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 3、校验是否过期，否 返回401
        Long userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Long.class);
        String tokenKey = "token:"+userId;
        String redisToken = redisTemplate.opsForValue().get(tokenKey);
        if (StringUtils.isEmpty(redisToken)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if (!redisToken.equals(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 4、token 续期
        redisTemplate.expire(tokenKey,60, TimeUnit.MINUTES);

        // 5、放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
